<?php

/**
 *
 * Controller to manage a group.
 * @author Théo Chamley
 *
 */
class GestiongroupeController extends CodeBar_AbstractController {

	public function init() {
		CodeBar_AbstractController::init();
		$this->view->headTitle("Groupe");
		$r = $this->session()->user->getRoles();
		if(!($this->session()->user->connected)) {
			$this->_helper->redirector('index');
		}
		$isAdmin = false;
		foreach ($r as $role) {
			$isAdmin = $isAdmin || ($role->getName() == 'AdminGroupe');
		}
		if($this->session()->permissionactive != "GestionGroupe" || !$isAdmin) {
			$this->_helper->redirector('modulechoice','index');
		}
	}

	public function indexAction() {
		/*
		 * JS
		 */
		$this->view->headScript()->appendFile('/js/gestiongroupemain.js','text/javascript');
		/*
		 * CSS
		 */
		$this->view->headLink()->appendStylesheet('/css/site.css');

		$this->view->headTitle($this->view->title, 'PREPEND');

		$this->view->link = '/gestiongroupe/gestionmembres';
		$this->view->link2 = '/gestiongroupe/changecode';
		$this->view->link3 = '/gestiongroupe/changename';
	}

	public function gestionmembresAction() {
		$this->view->headTitle("Membres");
		$this->jQueryUIEnable();
		/*
		 * JS
		 */
		$this->view->headScript()->appendFile('/js/gestiongroupesecondary.js','text/javascript');
		$this->view->headScript()->appendFile('/js/disable.js','text/javascript');
		//$this->view->headScript()->appendFile('/js/TriUsers.js','text/javascript');

		/*
		 * CSS
		 */
		$this->view->headLink()->appendStylesheet('/css/stylesheet_gestionmembres.css');

		/*
		 * Getting the group's admins.
		 */
		$r = new Application_Model_RolesUsers();
		$admins = $r->getAdmins($this->session()->user->getGroupeActif()->getID());
		$this->view->adminslist = $admins;
		/*
		 * Getting the group's salers
		 */
		$vendeurs = $r->getVendeurs($this->session()->user->getGroupeActif()->getID());

		$form = new Application_Form_GestionGroupe_SuppressionMembreForm();
		$form2 = new Application_Form_GestionGroupe_AjoutMembreForm();
		if($this->getRequest()->isPost()) {
			/*
			 * We have 2 forms on the same page, we have to differentiate them.
			 */
			if($_POST['formname'] == 'suppression') {
				$formData = $this->getRequest()->getPost();
				if($form->isValid($formData)) {
					foreach($vendeurs as $v) {
						/*
						 * We look for the chosen salers.
						 */
						if($form->getElement($v)->isChecked()) {
							/*
							 * We delete them
							 */
							$r->removeVendeur($this->session()->user->getGroupeActif()->getID(),$v);
						}
					}
				}
			}
			/*
			 * We have 2 forms on the same page, we have to differentiate them.
			 */
			else if($_POST['formname'] == 'ajout') {
				try {
					/*
					 * We create a new user from the login
					 */
					$user = Application_Model_User::getByLogin(strstr($_POST['vendeur'], ' ', true));
					/*
					 * If this user has to password...
					 */
					if($user->getPwd() == '') {
						/*
						 * If the 2 passwords are the same and the length is >= 6...
						 */
						if($_POST['pwd'] == $_POST['pwd_verif'] && mb_strlen($_POST['pwd']) >= 6) {
							/*
							 * We give this password to this user and register him as a saler
							 */
							$user->changePwd(md5($_POST['pwd']));
							$r->addMembre(1,strstr($_POST['vendeur'], ' ', true),$this->session()->user->getGroupeActif()->getID());

						} else if(mb_strlen($_POST['pwd']) >= 6) {
							$this->view->error = 'Les mots de passe fournis ne sont pas identiques.';

						} else {
							$this->view->error = 'Le mot de passe doit faire plus de 6 caractères.';
						}
					}
					/*
					 * If the user already has a password in
					 * the DB.
					 */
					else if($_POST['pwd'] != '') {
						/*
						 * The user is now a saler for this group.
						 */
						$r->addMembre(1,strstr($_POST['vendeur'], ' ', true),$this->session()->user->getGroupeActif()->getID());
						/*
						 * We display an error telling that the password was not changed
						 */
						$this->view->error = 'L\'utilisateur a déjà un mot de passe : il a bien été ajouté en tant que vendeur, mais son mot de passe n\'a pas été modifié.';
					} else {
						/*
						 * The user is now a saler for this group.
						 */
						$r->addMembre(1,strstr($_POST['vendeur'], ' ', true),$this->session()->user->getGroupeActif()->getID());
					}
				} catch(Zend_Exception $e) {
					$this->view->error = $e->getMessage();
				}
			}
			$this->redirect();
		}
		$form = new Application_Form_GestionGroupe_SuppressionMembreForm();
		$form2 = new Application_Form_GestionGroupe_AjoutMembreForm();
		$this->view->form = $form;
		$this->view->form2 = $form2;
	}

	public function changenameAction() {
		$this->view->headTitle("Nom");
		/*
		 * JS
		 */
		$this->view->headScript()->appendFile('/js/gestiongroupesecondary.js','text/javascript');

		/*
		 * CSS
		 */
		$this->view->headLink()->appendStylesheet('/css/stylesheet_changenomgroupe.css');

		$form = new Application_Form_GestionGroupe_ChangeNameForm();
		$this->view->form = $form;
		if($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if($form->isValid($formData)) {
				/*
				 * We are changing the name of the active group.
				 */
				$groupe = $this->session()->user->getGroupeActif();
				try {
					$groupe->changeName($form->getValue('nom'));
				} catch(Zend_Exception $e) {
					$this->view->error = $e->getMessage();
				}
			} if(!isset($e)) {
				$this->redirect('index');
			}
		}
	}

	public function changecodeAction() {
		$this->view->headTitle("Code");
		/*
		 * JS
		 */
		$this->view->headScript()->appendFile('/js/gestiongroupesecondary.js','text/javascript');

		/*
		 * CSS
		 */
		$this->view->headLink()->appendStylesheet('/css/stylesheet_changecodegroupe.css');

		$form = new Application_Form_GestionGroupe_ChangeCodeForm();
		$this->view->form = $form;
		if($this->getRequest()->isPost()) {
			$formData = $this->getRequest()->getPost();
			if($form->isValid($formData)) {
				$groupe = $this->session()->user->getGroupeActif();
				try {
					$groupe->changeCode($form->getValue('code'));
				} catch(Zend_Exception $e) {
					$this->view->error = $e->getMessage();
				}
			} if(!isset($e)) {
				$this->redirect('index');
			}
		}
	}

	/**
	 *
	 * Internal action used with Ajax for
	 * jQuery autocomplete.
	 */
	public function searchusersAction() {
		$request = $this->getRequest();
		$term = $request->getParam('term');
		$results = Application_Model_User::search($term);
		$users = array();
		foreach ($results as $user) {
			$users[$user->getLogin()] = $user->getLogin().' - '.$user->getNom().' '.$user->getPrenom();
		}
		$this->_helper->json(array_values($users));
	}
}